package com.violet.detective.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.violet.detective.entity.Defect;
import com.violet.detective.search.DefectSearchParameter;
import com.violet.detective.service.DefectService;
import com.violet.detective.util.ERCode;
import com.violet.detective.util.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/defect")
public class DefectController {

    @Resource
    private DefectService defectService;

    @PostMapping("/add")
    public R addDefect(@RequestBody Defect defect) {
        boolean result = defectService.addDefect(defect);
        return result ? R.ok() : R.error();
    }

    @PostMapping("/update")
    public R updateDefect(@RequestBody Defect defect) {
        boolean result = defectService.editDefect(defect);
        return result ? R.ok() : R.error();
    }

    @DeleteMapping("/deleteDefect/{id}")
    public R deleteDefect(@PathVariable Integer id) {
        boolean isSuccess = defectService.deleteDefect(id);
        return isSuccess ? R.ok() : R.error();
    }

    @GetMapping("/getDefectById/{id}")
    public R getDefectById(@PathVariable Integer id) {
        return R.ok(defectService.getDefectById(id));
    }

    @PostMapping("/search")
    public R searchDefects(@RequestBody DefectSearchParameter searchParameter) {
        List<Defect> result = defectService.searchDefects(searchParameter);
        return R.ok(result);
    }

    @PostMapping("/page-search")
    public R searchDefects(
            @RequestBody DefectSearchParameter searchParameter,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size
    ) {
        Page<Defect> resultPage = defectService.searchDefects(searchParameter, page, size);
        return R.ok(resultPage);
    }

    @GetMapping("/defects")
    public R findAllDefects() {
        List<Defect> result = defectService.findAllDefects();
        return R.ok(result);
    }

    @GetMapping("/page-defects")
    public R findAllDefects(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size
    ) {
        Page<Defect> resultPage = defectService.findAllDefects(page, size);
        return R.ok(resultPage);
    }

}
